package com.daoshu.mds.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daoshu.component.page.PageConstants;
import com.daoshu.mds.system.mapper.PersonMapper;
import com.daoshu.mds.system.service.*;
import com.daoshu.system.bo.PersonBo;
import com.daoshu.system.bo.PersonContentBO;
import com.daoshu.system.entity.*;
import com.daoshu.system.qo.PersonQO;
import com.daoshu.system.utils.ListUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhaoyanjiang
 * @since 2018-09-17
 */
@Service
public class PersonServiceImpl extends ServiceImpl<PersonMapper, PersonEntity> implements IPersonService {
	@Resource
	private PersonMapper personMapper;

	@Autowired
	private IAccountService accountService;

	@Autowired
	private IAccountRoleService accountRoleService;

	@Autowired
	private IRoleService roleService;

	@Autowired
	private IOrganizationPersonService organizationPersonService;

	@Autowired
	private IOrganizationService organizationService;

	@Override
	public IPage<PersonEntity> getPage(PersonBo personBo) {
		PersonEntity condition = new PersonEntity();
//		BeanUtils.copyProperties(personBo, condition);
//
//		String name = condition.getName();
//
//		condition.setName(null);
//		QueryWrapper<PersonEntity> queryWrapper = new QueryWrapper<>(condition);
//		if (null != name){
//			queryWrapper.or().like("name_", "%" + name + "%");
//			queryWrapper.or().likeLeft("address_", "%" + name);//组织查询
//			queryWrapper.or().like("number_", "%" + name + "%");
//			queryWrapper.or().like("police_code_", "%" + name + "%");
//		}
//
//		IPage<PersonEntity> page = this.page(new Page<>(personBo.getStart(), personBo.getSize()), queryWrapper);
		IPage<PersonEntity> personPage = new Page<>();
		personPage.setRecords(personMapper.pagePerson(personBo,personBo.getStart()>0?personBo.getStart()-1:personBo.getStart(),personBo.getSize()<=0?10:personBo.getSize()));
		personPage.setTotal(personMapper.countPagePerson(personBo));
		return getPersonAccount(personPage);
	}

	private IPage<PersonEntity> getPersonAccount(IPage<PersonEntity> page){
		if (CollectionUtils.isNotEmpty(page.getRecords())) {
			Set<String> ids = new HashSet<>();
			page.getRecords().forEach(item -> {
				ids.add(item.getId());
			});
			if (CollectionUtils.isNotEmpty(ids)) {
				List<AccountEntity> accounts = accountService
						.list(new QueryWrapper<AccountEntity>().in("person_id_", ids));
				if (CollectionUtils.isNotEmpty(accounts)) {
					// 获取此用户角色信息
					this.getRoleByAccountId(accounts);

					Map<String, AccountEntity> result = convertToMap(accounts);
					page.getRecords().forEach(item -> {
						if(result.containsKey(item.getId())) {
							item.setAccountEntity(result.get(item.getId()));
						}
					});
				}

				// 获取组织机构
				getOrgByParentId(page.getRecords());
			}
		}
		return page;
	}

	/**
	 * 获取组织机构数据
	 * @param persons
	 */
	private void getOrgByParentId(List<PersonEntity> persons) {
		Set<String> personIds = new HashSet<>();
		persons.forEach(item -> personIds.add(item.getId()));
		List<OrganizationPersonEntity> organizationPersonEntities = organizationPersonService
				.list(new QueryWrapper<OrganizationPersonEntity>()
						.in("person_id_", personIds));
		if (CollectionUtils.isNotEmpty(organizationPersonEntities)) {
			Set<String> orgIds = new HashSet<>();
			Map<String, String> personToOrganization = new HashMap<>();
			organizationPersonEntities.forEach(item -> {
				if (item.getOrgId() != null) {
					orgIds.add(item.getOrgId());
					personToOrganization.put(item.getPersonId(), item.getOrgId());
				}
			});
			Map<String, OrganizationEntity> organizationMap = this.convertToOrganizationMap(
					organizationService.list(new QueryWrapper<OrganizationEntity>().
							in("id_", orgIds)));
			persons.forEach(item -> item.setOrganizationEntity(organizationMap.get(personToOrganization.get(item.getId()))));
		}
	}

	private Map<String, OrganizationEntity> convertToOrganizationMap(List<OrganizationEntity> organizationEntities) {
		Map<String, OrganizationEntity> result = new HashMap<>();
		if (CollectionUtils.isNotEmpty(organizationEntities)) {
			organizationEntities.forEach(item -> result.put(item.getId(), item));
		}
		return result;
	}

	private void getRoleByAccountId(List<AccountEntity> accounts) {
		Set<String> accountIds = new HashSet<>();
		accounts.forEach(item -> accountIds.add(item.getId()));
		List<AccountRoleEntity> accountRoleEntities = accountRoleService
				.list(new QueryWrapper<AccountRoleEntity>()
						.in("account_id_", accountIds));
		if (CollectionUtils.isNotEmpty(accountRoleEntities)) {
			Set<String> roleIds = new HashSet<>();
			Map<String, String> accountToRole = new HashMap<>();
			accountRoleEntities.forEach(item -> {
				if (item.getRoleId() != null) {
					roleIds.add(item.getRoleId());
					accountToRole.put(item.getAccountId(), item.getRoleId());
				}
			});
			Map<String, RoleEntity> roleMap = this.convertToRoleMap(
					roleService.list(new QueryWrapper<RoleEntity>().
					in("id_", roleIds)));
			accounts.forEach(item -> item.setRoleEntity(roleMap.get(accountToRole.get(item.getId()))));
		}
	}

	private Map<String, RoleEntity> convertToRoleMap(List<RoleEntity> roleEntities) {
		Map<String, RoleEntity> result = new HashMap<>();
		if (CollectionUtils.isNotEmpty(roleEntities)) {
			roleEntities.forEach(item -> result.put(item.getId(), item));
		}
		return result;
	}

	private Map<String, AccountEntity> convertToMap(List<AccountEntity> accounts){
		Map<String, AccountEntity> result = new HashMap<>();
		accounts.forEach(item -> result.put(item.getPersonId(), item));
		return result;
	}

	@Override
	public IPage<PersonContentBO> queryPersonPage(PersonQO qo) {
		Page<PersonContentBO> page = new Page<>(qo.getStart(), qo.getSize());
		qo.setPersonIds(ListUtils.removeNullElement(qo.getPersonIds()));
		return personMapper.queryPerson(page,qo);
	}

	@Override
	public List<PersonContentBO> queryPersonList(List<String> personIds) {
		if(personIds==null||personIds.isEmpty()) {
			return new ArrayList<>();
		}
		Page<PersonContentBO> page = new Page<>(PageConstants.PAGE_NUM_START, personIds.size());
		PersonQO qo = new PersonQO();
		qo.setPersonIds(ListUtils.removeNullElement(personIds));
		return Optional.ofNullable(personMapper.queryPerson(page,qo).getRecords()).orElse(new ArrayList<>());
	}

	@Override
	public PersonEntity getByAccountId(String id) {
		AccountEntity account = accountService.getById(id);
		if(account != null){
			return this.getById(account.getPersonId());
		}
		return null;
	}

	/**
	 * 根据组织机构查询人员列表
	 *
	 * @param orgId 组织机构编号
	 * @return
	 */
	@Override
	public List<PersonEntity> getPersonsByOrgId(String orgId) {
		return personMapper.getPersonsByOrgId(orgId);
	}
}
